package logic

import (
	"context"
	"encoding/json"
	"house/models/cache"
	"house/models/mysql"
	"time"

	"house/consultrpc/consultrpc"
	"house/consultrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ConsultListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewConsultListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ConsultListLogic {
	return &ConsultListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ConsultListLogic) ConsultList(in *consultrpc.ConsultListRequest) (*consultrpc.ConsultListResponse, error) {
	// todo: add your logic here and delete this line
	var consults []mysql.Consult
	result, _ := cache.Rdb.Get(l.ctx, "ConsultList").Result()
	if result == "" {
		mysql.DB.Debug().Find(&consults)

		marshal, _ := json.Marshal(consults)

		cache.Rdb.Set(l.ctx, "seekList", marshal, time.Minute*15)

	} else {
		json.Unmarshal([]byte(result), &consults)
	}

	var ConsultList []*consultrpc.ConsultList
	for _, consult := range consults {
		list := consultrpc.ConsultList{
			Problem: consult.Problem,
			HouseId: int64(consult.HouseId),
			UserId:  int64(consult.UserId),
		}
		ConsultList = append(ConsultList, &list)
	}
	return &consultrpc.ConsultListResponse{
		List: ConsultList,
	}, nil
}
